package org.zhangxiao.paladin2.admin.autoconfigure;

import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.zhangxiao.paladin2.admin.cfg.ISysCfgService;
import org.zhangxiao.paladin2.admin.cfg.SysCfgServiceWithRedisCache;
import org.zhangxiao.paladin2.admin.shiro.AdminAuthorizationInfoStorage;
import org.zhangxiao.paladin2.admin.shiro.AdminAuthorizationInfoStorageRedis;

@Configuration
@ConditionalOnClass(RedisConnectionFactory.class)
@EnableCaching
@AutoConfigureBefore(Paladin2AdminAutoConfiguration.class)
public class Paladin2RedisAutoConfiguration {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // RedisTemplate的key默认序列化器问题
        // https://blog.csdn.net/skymouse2002/article/details/80736577
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);

        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }


    @Bean
    public ISysCfgService sysCfgService() {
        return new SysCfgServiceWithRedisCache();
    }

    @Bean
    public AdminAuthorizationInfoStorage adminAuthorizationInfoStorage() {
        return new AdminAuthorizationInfoStorageRedis();
    }
}
